(function(){

var m_data = getLocalData(KEY_QIYI_DATA) || {};

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    switch(request.type){
        case "setData":
            m_data = getLocalData(request.key) || {};
            //merge
            _.each(request.value, function(value, key){m_data[key] = value});
            setLocalData(m_data, request.key);
            sendResponse && sendResponse();
            break;
        case "getData":
            sendResponse && sendResponse(getLocalData(KEY_QIYI_DATA));
            break;
        case "loadContents":
               loadContents(sender.tab, request.list);
            sendResponse && sendResponse();
            break;
          case "createPage":
            request = request || {};
            //fetch new data
            chrome.tabs.create({url:request.url, active:request.active});
            break;
          case "removePage":
            removePage(sender.tab);
            break;
    }
});

//send message to content.js or extension pages
function sendMessage(data) {
    data = data || {};
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, data);
     });
}

function loadContents(tab, list){
    //clone
    list = list ? list.slice(0) : [];
    loadNext();
    //
    function loadNext(){
        var name = list.shift();
        if(name){
            injectContent(tab, name, null, arguments.callee);
        }else{
            sendMessage({type:"onLoadContentComplete"});
        }
    }
}

function injectContent(tab, name, type, callback){
    type = type || "js";
    if(tab && name){
        var nameRegex = /\w+\.[a-z]{2,8}$/i;
        //whether contains postfix,such as '.js'
        if(!nameRegex.test(name)){
            name += "." + type;
        }
        if(type == "js"){
            chrome.tabs.executeScript(tab.id, {file:name}, callback);
        }else if(type == "css"){
            chrome.tabs.insertCSS(tab.id, {file:name}, callback);
        }
    }
}
    
}).call(this);